import { useTableScroll } from '@/hooks/useTableScroll';
import { getDetailList, retOrder } from '@/services/production-center';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { Link } from '@umijs/max';
import { Button, Select, message } from 'antd';
import { useRef, useState } from 'react';

const options = [
  {
    label: '不限',
    value: '',
  },
  {
    label: '待转账',
    value: 'WAIT_ENSURE',
  },
  {
    label: '转账处理中',
    value: 'WAIT_TRANS',
  },
  {
    label: '银行处理中',
    value: 'DEALING',
  },
  {
    label: '成功',
    value: 'SUCCESS',
  },
  {
    label: '失败',
    value: 'FAIL',
  },
  {
    label: '废弃',
    value: 'DISUSE',
  },
  {
    label: '退票',
    value: 'REFUND',
  },
];
const optionsEnum = options.reduce((obj, cur) => {
  obj[cur.value] = { text: cur.label };
  return obj;
}, {} as any);
const ACSDetail = () => {
  const [count, setCount] = useState(0);
  const tableScrollHeight = useTableScroll({}, count);
  const actionRef = useRef<ActionType>();
  const [mainTableParams, setMainTableParams] = useState({
    status: '',
  });
  const columns: ProColumns<any>[] = [
    {
      title: '批次创建时间',
      dataIndex: 'createTime',
      valueType: 'dateRange',
      width: 180,
      order: 1,
      search: {
        transform: (value: any) => {
          if (!value) return null;
          return {
            minCreateTime: value[0],
            maxCreateTime: value[1],
          };
        },
      },
      hideInTable: true,
    },
    {
      title: '订单编号',
      dataIndex: 'importBizNo',
      width: 160,
      order: 4,
    },
    {
      title: '外部批次号',
      dataIndex: 'importBatchNo',
      width: 160,
      order: 2,
      render: (_, record) => {
        return (
          <Link
            to={`/production-center/acs/acs-record?importBatchNo=${record.importBatchNo}`}
            className="text-[#00bdff]"
          >
            {record.importBatchNo}
          </Link>
        );
      },
    },
    {
      title: '支付宝订单号',
      dataIndex: 'payFundOrderId',
      width: 160,
      hideInSearch: true,
    },
    {
      title: '收款账号',
      dataIndex: 'identity',
      width: 160,
      order: 3,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      width: 160,
      hideInSearch: true,
    },
    {
      title: '金额',
      dataIndex: 'transAmount',
      width: 160,
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 160,
      order: 5,
      render: (_, record) => {
        const colors = {
          WAIT_TRANS: 'text-[#00bdff]',
          DISUSE: 'text-[red]',
        } as Record<string, string>;
        return (
          <div className={`${colors[record.status]}`}>
            {optionsEnum[record.status].text}
          </div>
        );
      },
      renderFormItem: () => {
        return <Select options={options} defaultValue={''}></Select>;
      },
    },
    {
      title: '失败原因',
      dataIndex: 'errorMsg',
      width: 160,
      hideInSearch: true,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 160,
      hideInSearch: true,
    },
    // {
    //   title: '电子回单',
    //   dataIndex: 'receiptStatus',
    //   width: 160,
    //   hideInSearch: true,
    //   render: (_, record) => {
    //     return (
    //       <span>{record.receiptStatus === 'SUCCESS' ? '成功' : record.receiptStatus === 'INIT' ? '初始化' : record.receiptStatus === 'FAIL' ? '失败' : record.receiptStatus === 'PROCESS' ? '处理中' : '-'}</span>
    //     );
    //   },
    // },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: 100,
      fixed: 'right',
      render: (_, record) => [
        <span className="text-[#00bdff]" onClick={() => { downloadFile(record) }}>下载回单</span>
      ],
    },
  ];

  const downloadFile = (record: any) => {
    const { id } = record
    retOrder({ id: id }).then((res: any) => {
      if (res.success) {
        let ele = document.createElement('a')
        ele.download = ""
        ele.style.display = 'none'
        ele.href = res.data.downloadUrl
        ele.target = "_blank"
        document.body.appendChild(ele);
        ele.click();
        document.body.removeChild(ele);
      } else {
        message.error(res.resultMessage);
      }
    })
  }

  return (
    <div>
      <ProTable
        scroll={{ y: tableScrollHeight, x: 200 }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        dateFormatter="YYYY-MM-DD 00:00:00"
        request={async (params: any) => {
          console.log(params);
          const { current, pageSize, ...rest } = params;
          const searchData = {
            pageNo: current - 1,
            pageSize: pageSize,
            ...rest,
          };
          const { data, count } = (await getDetailList(searchData)) as any;
          setMainTableParams({
            ...mainTableParams,
            ...searchData,
          });
          setCount(count + 1);
          return {
            data: data,
            total: count,
            success: true,
          };
        }}
        columns={columns}
        pagination={{
          defaultPageSize: 20,
          showQuickJumper: true,
          showSizeChanger: true,
        }}
        actionRef={actionRef}
        cardBordered
        columnsState={{
          defaultValue: {
            option: { fixed: 'right', disable: true },
          },
        }}
        toolBarRender={() => [
          <Button
            key="button"
            type="primary"
            onClick={() => {
              const formDom = document.createElement('form');
              formDom.setAttribute('type', 'hidden');
              formDom.setAttribute('target', '_black');
              formDom.setAttribute('method', 'get');
              formDom.setAttribute(
                'action',
                '/api/merchant/safe-pay-order/export-detail',
              );
              const inputDom = document.createElement('input');
              inputDom.setAttribute('type', 'hidden');
              inputDom.setAttribute('name', 'searchModelJson');
              inputDom.setAttribute('value', JSON.stringify(mainTableParams));

              formDom.append(inputDom);
              document.body.append(formDom);
              formDom.submit();
            }}
          >
            导出
          </Button>,
        ]}
      />
    </div>
  );
};

export default ACSDetail;
